package algorithms.paixu;

import edu.princeton.cs.algs4.StdRandom;

/**
 * @功能
 * @创建时间 2020/12/15
 * 快速排序
 * 将首个值当中间值通过和其对比进行切分，把小的放左边大的放右边并分成2的指数倍递归交换方法类似于选择排序，左边找个大的右边逆序找个小的交换顺序并循环最后最后把右边找到的小的放最左边
 */
public class Quick {
    public static void sort(Comparable[] a){
        StdRandom.shuffle(a);
        sort(a,0,a.length - 1);
    }

    public static void main(String[] args) {
        Integer[] a = {8,1,4,9,0,3,5,2,7,6};
        sort(a,0,a.length - 1);
    }
    private static void sort(Comparable[] a,int lo,int hi){
        if(hi <= lo) return;
        int j = partition(a,lo,hi);
        sort(a,lo,j-1);
        sort(a,j+1,hi);
    }
    public static  boolean less(Comparable v,Comparable w){
        return v.compareTo(w)<0;
    }
    public static void exch(Comparable[] a,int i,int j){
        Comparable t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
    private static void show(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
    public static boolean isSorted(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            if(less(a[i],a[i-1]))
                return false;

        }
        return true;
    }
    private static int partition(Comparable[] a,int lo,int hi){
        int i = lo, j= hi + 1;
        Comparable v = a[lo];
        while (true){
            while(less(a[++i],v)) {if(i==hi) break;};
            while(less(v,a[--i]))
            {if(j==lo) break;};
            if(i>=j) break;
            exch(a,i,j);
        }
        exch(a,lo,j);
        return j;
    }
}
